<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>数组去重</title>
</head>

<body>
    <script>
        let arrList = [1, 2, 3, 4, 4, 6, 5, 2, 1, 1, 6, 6, 4, 1, 1, 1, 1];
        let otherList = [1, 2 ,1 ,2, true, false, 'true',true, 'true', {}, {}]

        // 数组去重方法1，用indexOf()
        const arrayDuplication1 = (arr) => {
            let newArr = []
            arr.forEach((item, i) => {
                if (newArr.indexOf(arr[i]) === -1) {
                    newArr.push(arr[i])
                }
            })
            return newArr
        };
        // console.log(arrayDuplication1(arrList), 'arrayDuplication1');

        // 数组去重方法2，用includes()
        const arrayDuplication2 = (arr) => {
            let newArr = []
            arr.map((item, i) => {
                if(!newArr.includes(arr[i])) {
                    newArr.push(arr[i])
                }
            })
            return newArr
        }
        // console.log(arrayDuplication2(arrList), 'arrayDuplication2')

        // 数组去重方法3，双重for循环 + splice()
        const arrayDuplication3 = (arr) => {
            for(let i = 0; i < arr.length; i++) {
                for(let j = i + 1; j < arr.length; j++) {
                    // console.log(arr[i] + '=============' + arr[j]);
                    if(arr[i] === arr[j]) {
                        arr.splice(j, 1)
                        j-- //由于splice方法方法将当前下表为 j 的元素删除掉了，下次循环会从 j+1 开始，但是删除当前元素后，数组长度 -1 第 j+1 个元素就相当于在下一个元素前跳了一个元素，需要 j-1 回到当前位置
                        // console.log(arr);
                    }
                }
            }
            return arr
        }
        // console.log(arrayDuplication3(arrList), 'arrayDuplication3');
        // console.log(arrayDuplication1(otherList), 'arrayDuplication3');

        // 数组去重方法4，借用对象的 hasOwnProperty 属性，实现数组去重
        const arrayDuplication4 = (arr) => {
            let obj = {}
            return arr.filter((item, i) => {
                return obj.hasOwnProperty(typeof item + item) ? false : obj[typeof item + item] = 1
            })
        }
        // console.log(arrayDuplication4(otherList), 'arrayDuplication4');

        // 最优方法，借用ES6，代码量少
        // 数组去重方法5，借用ES6中的Set结构，可以对数组进行去重
        const arrayDuplication5 = (arr) => {
            return Array.from(new Set(arr))
        }
        // console.log(arrayDuplication5(arrList), 'arrayDuplication5');
    </script>
</body>

</html>